<?php

namespace app\admin\service;

use app\admin\model\Orders;
use app\admin\model\User;
use app\common\service\OrderStatus;

class WorkSpace
{
    /**
     * 获取业务数据
     *
     * @param int $begin 开始时间，格式为UNIX时间戳
     * @param int $end 结束时间，格式为UNIX时间戳
     * @return array
     */
    public function getBusinessData($begin,$end)
    {
        $strbegin = date('Y-m-d', $begin);
        $strend = date('Y-m-d', $end);

        // 营业额
        $turnoverAmount = Orders::where('checkout_time', 'between time', [$strbegin, $strend])->where('status', OrderStatus::COMPLETED)->sum('amount');

        // 新增用户数
        $newUserCount = User::where('jointime', 'between time', [$begin, $end])->count();

        $orderCount = Orders::where('checkout_time', 'between time', [$strbegin, $strend])->count();
        // 	有效订单
        $validOrderCount = Orders::where('checkout_time', 'between time', [$strbegin, $strend])->where('status', OrderStatus::COMPLETED)->count();
        // 订单完成率
        $orderFulfillmentRate = 0;
        if ($validOrderCount > 0) {
            $orderFulfillmentRate = $validOrderCount / $orderCount;
        }

        // 平均客单价
        $averageRoomRate = 0;
        if ($turnoverAmount > 0) {
            $averageRoomRate = $turnoverAmount / $validOrderCount;
        }

        return [
            'turnoverAmount' => $turnoverAmount,
            'orderFulfillmentRate' => $orderFulfillmentRate,
            'averageRoomRate' => $averageRoomRate,
            'newUserCount' => $newUserCount,
            'validOrderCount' => $validOrderCount,
        ];
    }
}
